<?php

namespace app\service;

use app\exception\ErrnoPlus;
use app\model\DeviceInfoTableModel;
use share\exception\ApiException;
use share\exception\Errno;
use share\service\BaseModelService;
use share\service\UserBaseService;
use share\service\UserDetailService;
use share\utils\Helper;

class DeviceInfoTableService extends BaseModelService
{

    public static function getModel(){
        return new DeviceInfoTableModel;
    }

    public static function getByIotId($iotId)
    {
        $data = DeviceInfoTableModel::get(['iot_id' => $iotId]);
        return DeviceInfoTableModel::formatModelData($data);
    }

    public static function getAllByIotIds($iotIds)
    {
        if (count($iotIds) < 1) {
            return [];
        }
        $iotIds = Helper::arraySmartUnique($iotIds);
        return self::getAllByFilter([
            'iot_id' => ['in', $iotIds],
        ]);
    } 

    /**
     * 比较和更新设备基本信息
     */
    public static function compareAndUpsert($newItem,$originList){
        $origin = null;
        if(isset($newItem['device_name'])){
            $origin = Helper::filterOne($originList,['device_name' => $newItem['device_name'] ]);
        }
        else if(isset($newItem['iot_id'])){
            $origin = Helper::filterOne($originList,['iot_id' => $newItem['iot_id'] ]);
        }
        else{
            throw new ApiException("the base new item must have device_name or iot_id",Errno::COMMON_SYSTEM_ERROR);
        }
        if(empty($origin)){
            if(!isset($newItem['extend_num'])){
                $newItem['extend_num'] = 0;
            }  
            self::add($newItem);
        }
        else{
            $update = [];
            foreach($newItem as $key => $val){
                if($key == 'device_name' || $key == 'iot_id'){
                    continue;
                }
                if($val != $origin[$key]){
                    $update[$key] = $val;
                }
            }
            if(count($update) > 0){
                self::update($origin['device_name'],$update);
            }
        }
    }


    public static function buildCondition($filter)
    {
        $res = [];
        if(isset($filter['deviceName']) && !empty($filter['deviceName'])){
            $res['device_name'] = $filter['deviceName'];
        }
        if(isset($filter['iotId']) && !empty($filter['iotId'])){
            $res['iot_id'] = $filter['iotId'];
        }
        return $res;
    }

    public static function getShareBindingInfoByIotId($iotId){
        $device = self::getByIotId($iotId);
        if(empty($device)){
            throw new ApiException("device is no exist",ErrnoPlus::COMMON_ERROR);
        }
        $share = UserDeviceShareService::getAllByMainId([$iotId]);
        $userIds = array_column($share,'admin_uid');
        $shareUserIds = array_column($share,'share_uid');
        $allUserIds = array_merge($userIds,$shareUserIds);
        $userInfos = UserBaseService::getAll($allUserIds);
        $userDetails = UserDetailService::getAll($allUserIds);
        $deviceInfo = [];
        $shareInfo = [];
        $shareRules = UserDeviceShareRuleService::getAll(array_column($share,'id'));
        foreach($share as $shareItem){           
            if(empty($deviceInfo)){
                $uid = $shareItem['admin_uid'];
                $user = Helper::filterOne($userInfos,['id'=>$uid]);
                $userDetail = Helper::filterOne($userDetails,['id'=>$uid]);
                $deviceInfo = [
                    'userId' => $user['user_id'],
                    'identityId' => $user['identity_id'],
                    'phone' => $user['phone'],
                    'email' => $user['email'],
                    'serverSite' => $userDetail['server_site'],
                    'iotId' => $device['iot_id'],
                    'deviceName' => $device['device_name'],
                    'chNum' => $device['ch_num'],
                    'extendNum' => $device['extend_num'],
                ];
            }
            $uid = $shareItem['share_uid'];
            $user = Helper::filterOne($userInfos,['id'=>$uid]);
            $userDetail = Helper::filterOne($userDetails,['id'=>$uid]);
            $rule = Helper::filterOne($shareRules,['id'=>$shareItem['id']]);
            $shareInfo[] = [
                'userId' => $user['user_id'],
                'identityId' => $user['identity_id'],
                'phone' => $user['phone'],
                'email' => $user['email'],
                'nickName' => $userDetail['nick_name'],
                'shareRule' =>  $rule['rule'],
            ];
        }
        return  [
            'deviceInfo' => $deviceInfo,
            'shareInfo' => $shareInfo,
        ];
    }

}
